package com.yxy.springcloud.framework.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

/**
 * 路由前置拦截，增加cors支持
 *
 * @author yuxiaoyang
 */
//@Component
//@ConfigurationProperties(prefix = "filter")
@Slf4j
public class CorsFilter extends ZuulFilter {

  @Override
  public String filterType() {
    return FilterConstants.PRE_TYPE;
  }

  @Override
  public int filterOrder() {
    return 1;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() throws ZuulException {
    RequestContext context = getCurrentContext();
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, x-token");
    response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,PATCH");
    response.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
    response.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");

    if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
      context.setSendZuulResponse(false);//令zuul过滤该请求，不对其进行路由
      context.setResponseStatusCode(200);
      return null;
    }
    return null;
  }
}
